﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices;
using System.DirectoryServices.Protocols;
using System.Net;
using System.Security;
using System.Security.Permissions;
/// <summary>
/// Summary description for OpenLDAP
/// </summary>
/// 
[DirectoryServicesPermission(SecurityAction.LinkDemand, Unrestricted = true)]
public class OpenLDAP : Connector
{
    DirectoryEntry de;
    string Domain;
    public OpenLDAP()
    {
        Domain = ConfigurationManager.AppSettings["Domain"];
        GetSettingsFromConfig();
        GetPropertiesFromConfig();
        GetConnect();
    }

    public override dynamic GetConnect()
    {
        de = new DirectoryEntry();
        de.Path = Domain;
        de.AuthenticationType = AuthenticationTypes.Secure;
        de.Username = Login;
        de.Password = Password;

        return de;
    }
    public override List<dynamic> GetUsers()
    {

        return null;
    }
    public override void ChangeUserProperty(dynamic User, CatalogProperty[] Props)
    {

    }
    public override List<dynamic> FindUsers(CatalogProperty[] Props, bool OneEnough)
    {
       
        
        return null;
    }
    public override dynamic FindUser(CatalogProperty[] Props, bool OneEnough)
    {
        DirectorySearcher deSearch = new DirectorySearcher();

        deSearch.SearchRoot = de;
        deSearch.Filter = "(&(objectClass=user) ";
        foreach (CatalogProperty prop in Props)
        {

            deSearch.Filter += "(" + prop.Property + "=" + prop.Value + ")) ";
          
            //Command += String.Format(" {0} '{1}' ", prop.Property, prop.Value);
        }
        SearchResult result = deSearch.FindOne();
        DirectoryEntry user = result.GetDirectoryEntry();

        return user;
    }
    public override string CreateUser(CatalogProperty[] Props)
    {
        return "NotImplemented";
    }
    public override bool ChangePassword(dynamic User, string Password)
    { 
        User.Invoke("SetPassword", new object[] { Password });
        User.CommitChanges(); 
        return true;
    }
}

